package commSql

import (
	"gitee.com/fierce_wolf/go-fox-edge-common/commEnv"
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/FileName"
	"log"
	"os"
)

var (
	schema     *entitySchema
	SQL        entitySQL
	Client     *mysqlClient
	Fox        foxSqlService
	SqlBuilder sqlBuilder
)

func init() {
	Client = &mysqlClient{}
	
	schema = &entitySchema{}
	schema.schema = make(map[string]interface{})
}

func Register(entityType string) {
	schema.registerSchema(entityType)
}

func GetEntityType() []string {
	return schema.getRegisters()
}

func GetDBType() string {
	dbType, _ := commEnv.GetArg("envDBType")
	if dbType == "sqlite3" {
		return "sqlite3"
	}

	return "mysql"
}

func buildMySQLOption() *SQLOption {
	host, ok := commEnv.GetArg("mysql.host")
	if !ok {
		panic("缺失参数：mysql.host")
	}

	port, ok := commEnv.GetArg("mysql.port")
	if !ok {
		panic("缺失参数：mysql.port")
	}

	username, ok := commEnv.GetArg("mysql.username")
	if !ok {
		panic("缺失参数：mysql.username")
	}

	password, ok := commEnv.GetArg("mysql.password")
	if !ok {
		panic("缺失参数：mysql.password")
	}

	database, ok := commEnv.GetArg("mysql.database")
	if !ok {
		panic("缺失参数：mysql.database")
	}

	if host == "" {
		host = "localhost"
	}
	if port == "" {
		port = "3306"
	}
	if database == "" {
		database = "fox_edge"
	}

	// 定义数据库连接信息
	option := &SQLOption{}
	option.DriverName = "mysql"
	option.DataSource = username.(string) + ":" + password.(string) + "@tcp(" + host.(string) + ":" + port.(string) + ")/" + database.(string)

	return option
}

func buildSQLite3Option(fileName string) *SQLOption {
	option := &SQLOption{}
	option.DriverName = "sqlite3"
	option.DataSource = FileName.GetOsFilePath(commEnv.Service.WorkDir + "/data/" + fileName)

	// 使用MkdirAll创建缺省的目录
	err := os.MkdirAll(FileName.GetOsFilePath(commEnv.Service.WorkDir+"/data"), os.ModePerm)
	if err != nil {
		log.Fatalf("无法创建目录: %v", err)
	}

	return option
}
